from django.shortcuts import render, HttpResponse
from rest_framework.exceptions import APIException
from utils.logging import get_logger
from rest_framework.views import APIView
from utils.response import APIResponse
logger = get_logger()
from rest_framework.viewsets import ViewSet
from . import serializer
from . import models
from utils.response import APIResponse
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from lib import tx_sms
import re
from django.conf import settings

# 导入django缓存模块,由于没有配置，默认在内存，可以改到redis中缓存
from django.core.cache import cache

from .throttling import SMSThrottle

#登录接口
class LoginView(ViewSet):
    #多方式登录函数
    def login(self, request):
        # 逻辑写在序列化类中
        ser = serializer.LoginSerializer(data=request.data)

        ser.is_valid(raise_exception=True)  # 执行序列化类字段自己的校验规则，局部钩子，全局钩子
        token = ser.context.get('token')
        username = ser.context.get('username')
        return APIResponse(msg='登录成功', username=username, token=token)
    # 手机号登录方式
    def mobile_login(self, request):
        # 逻辑写在序列化类中
        ser = serializer.MobileLoginSerializer(data=request.data)

        ser.is_valid(raise_exception=True)  # 执行序列化类字段自己的校验规则，局部钩子，全局钩子

        token = ser.context.get('token')
        username = ser.context.get('username')
        return APIResponse(msg='登录成功', username=username, token=token)

# 手机接口
class MobileView(ViewSet):
    # 校验手机号是否存在接口
    @action(methods=['GET'], detail=False)
    def mobile(self, request):
        # mobile=request.query_params.get('mobile')
        mobile = request.query_params.get('mobile')
        try:
            models.User.objects.get(mobile=mobile)
        except Exception:
            raise APIException('手机号不存在')

        return APIResponse(is_exisit=True)
    # 发送短信接口
    @action(methods=['GET'], detail=False, url_path='sms', throttle_classes=[SMSThrottle])
    def send_sms(self, request):
        mobile = request.query_params.get('mobile')
        if mobile and re.match('^1[3-9][0-9]{9}$', mobile):
            # 发送短信
            # 获取验证码，记录验证码（放到缓存中，默认还是缓存到内存）
            code = tx_sms.get_code()
            cache.set(settings.CACHE_SMS % mobile, code)

            # 调用发送短信函数
            res = tx_sms.send_sms(mobile, code)
            if res:
                return APIResponse(msg='短信发送成功')
            else:
                raise APIException('短信发送失败')
        else:
            raise APIException('手机号不合法')


# 保存，序列化类
# 自动生成路由，跟数据库打交道,create方法，
from rest_framework.viewsets import ViewSetMixin, GenericViewSet
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin
from .models import User


# class RegisterView(ViewSetMixin,GenericAPIView,CreateModelMixin)
class RegisterView(GenericViewSet, CreateModelMixin):
    queryset = User.objects.all()
    serializer_class = serializer.RegisterUserSerializer

    # def create(self, request, *args, **kwargs):
    #     # super().create(request, *args, **kwargs)
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     self.perform_create(serializer)
    #     return APIResponse(msg='注册成功')
    def create(self, request, *args, **kwargs):
        super().create(request, *args, **kwargs)

        return APIResponse(msg='注册成功')
